# -*- coding: utf-8 -*-
##############################################################################
#    ITGeeker技术奇客 https://www.itgeeker.net
#    Copyright 2020 ITGeeker <alanljj@gmail.com>
##############################################################################
"""
Python 3通过API给NAS里的电源获取电影字幕
TODO:
1. sort film dir by create date
"""
import json
from pathlib import Path
from sys import platform
import requests
import urllib.request


def rmdir(directory):
    directory = Path(directory)
    for item in directory.iterdir():
        if item.is_dir():
            rmdir(item)
        else:
            item.unlink()
    directory.rmdir()


def get_root_dir():
    root_dir = ''
    if platform == "linux" or platform == "linux2":
        print('linux')
        root_dir = Path('/volume1/video/film_new')
    elif platform == "darwin":
        print('OS X')
    elif platform == "win32":
        print('# Windows...')
        # root_dir = Path(r'D:\test')
        root_dir = Path(r'\\YOUR_NAS\video', 'film_new')
    return root_dir


def get_assrt_net_id(token, film_name, is_file, no_muxer, cnt):
    # cnt = '3'
    url_search = 'https://api.assrt.net/v1/sub/search?' + '&token=' + token + '&q=' + film_name \
                 + '&is_file=' + is_file+ '&no_muxer=' + no_muxer + '&cnt=' + cnt
    # rep_search = requests.get(url_search)
    print(url_search)
    # curl "https://api.assrt.net/v1/sub/search?&token=YOUR_TOKEN&q=2067&cnt=1"

    s = requests.session()
    s.keep_alive = False
    # s.headers = header
    rep_search = s.get(url_search)
    return rep_search


def get_assrt_sub_deail(token, id_sub):
    url_sub_detail = 'https://api.assrt.net/v1/sub/detail?' + '&token=' + token + '&id=' + str(id_sub)
    print(url_sub_detail)
    # curl "https://api.assrt.net/v1/sub/detail?&token=YOUR_TOKEN&id=659905"

    s = requests.session()
    s.keep_alive = False
    # s.headers = header
    rep_sub_detail = s.get(url_sub_detail)
    # rep_sub_detail = requests.get(url_search)
    return rep_sub_detail


def get_assrt_sub_user_quota(token):
    url_user_quota = 'https://api.assrt.net/v1/user/quota?' + '&token=' + token
    print(url_user_quota)
    # curl "https://api.assrt.net/v1/user/quota?&token=YOUR_TOKEN"
    s = requests.session()
    s.keep_alive = False
    # s.headers = header
    rep_user_quota = s.get(url_user_quota)
    # rep_user_quota = requests.get(url_search)
    print(rep_user_quota.text)
    status = rep_user_quota.status_code
    if status != 200:
        print('status code is: %s' % status)
        exit()
    user_quota_dict = json.loads(rep_user_quota.text)
    user_quota = user_quota_dict['user']['quota']
    return user_quota


if __name__ == '__main__':
    token = 'YOUR_API'
    root_dir = get_root_dir()
    print(root_dir)

    sub_ext = ['.ass', '.srt', '.smi', '.ssa', '.sub', '.idx']
    film_ext = ['.mkv', '.avi', '.mp4']
    dir_list = []
    no_sub_list = []
    have_sub_list = []
    small_dir_list = []
    # [x for x in root_dir.iterdir() if x.is_dir()]
    for x in root_dir.iterdir():
        # if root_dir.is_dir():
        if x.is_dir():
            dir_list.append(x)
    print('dir_list number:')
    print(len(dir_list))
    for d in dir_list:
        size = sum(f.stat().st_size for f in d.glob('**/*') if f.is_file())
        if size < 102400000:
            small_dir_list.append(d)
        # print(d)
        # print(str(round(size/1024/1024, 2)) + 'M')
        # print('--------------------------')
        cur_sub_list = []
        d_files = sorted(d.glob('**/*.*'))
        # d_files = list(pathlib.Path(d).glob(sub))
        for f in d_files:
            cur_sub_list.append(f.suffix)
        check = any(item in sub_ext for item in cur_sub_list)
        if check is True:
            print('There is subtitle for this folder: %s' % d)
            have_sub_list.append(d)
        else:
            no_sub_list.append(d)
    print('small dir list:')
    print(len(small_dir_list))
    print(small_dir_list)
    if len(small_dir_list) > 0:
        for sdl in small_dir_list:
            rmdir(sdl)
    print('----------rm small dir finished ----------------')

    print('have sub list number:')
    print(len(have_sub_list))
    print('no sub list number:')
    print(len(no_sub_list))
    # print(no_sub_list)
    # if len(no_sub_list) > 0:
    #     print(no_sub_list[0])
    #     print(no_sub_list[1])
    #     print(no_sub_list[2])
    #     print(no_sub_list[3])
    #     print(no_sub_list[4])
        # for nsl in no_sub_list:
        #     print(nsl)
    print('-------no sub and have sub nbr ------------')

    user_quota = get_assrt_sub_user_quota(token)
    if user_quota > 0:
        if len(no_sub_list) > 0:
            # film_name = 'Leap'
            # film_name = no_sub_list[0].stem
            # film_name = no_sub_list[0]
            for nsl in no_sub_list:
                print('nsl: ' + str(nsl))
                film_name = nsl.name
                print('film_name: ' + film_name)
                is_file = '1'
                no_muxer = '1'
                cnt = '8'
                if len(film_name) > 3:
                    rep_id = get_assrt_net_id(token, film_name, is_file, no_muxer, cnt)
                #     # print(rep_id.status)
                #     print(rep_id)
                    print(rep_id.status_code)
                #     print('rep_id type:' + str(type(rep_id)))
                #     print(rep_id.text)
                    rep_id_json = json.loads(rep_id.text)
                #     print(type(rep_id_json))
                    id_list = []
                    # if rep_id_json['sub']:
                    if 'sub' in rep_id_json:
                        ids_sub = rep_id_json['sub']['subs']
                        for i in ids_sub:
                            id_sub = i['id']
                            id_list.append(id_sub)
                        print(str(id_list))
                        print('**************************')

                        # sub details
                        if len(id_list) > 0:
                            for id_l in id_list:
                                rep_sub = get_assrt_sub_deail(token, id_l)
                                # print(rep_sub.status_code)
                                print(rep_sub)
                                print('rep_sub type:' + str(type(rep_sub)))
                                print(rep_sub.text)
                                rep_sub_json = json.loads(rep_sub.text)
                                print(rep_sub_json)
                                sub_zip_url_list = []
                                if 'sub' in rep_sub_json:
                                    sub_details = rep_sub_json['sub']['subs']
                                    for sd in sub_details:
                                        sub_filenames = sd['filelist']
                                        # sub_zip_url = sd['url']
                                        # sub_zip_filename = sd['filename']
                                        # print('@@@@@@@@@@@@@@@@@@@@@@@@@@')
                                        # sub_zip_url_list.append(sub_zip_url)
                                    # if len(sub_zip_url_list) > 0:
                                    #     for surl in sub_zip_url_list:
                                    #         # Download the file from `url` and save it locally under `file_name`:
                                    #         sub_zip_dl_name = nsl / sub_zip_filename
                                    #         print('sub_zip_file_name: %s' % sub_zip_dl_name)
                                    #         urllib.request.urlretrieve(surl, sub_zip_dl_name)
                                    if sub_filenames:
                                        for sfs in sub_filenames:
                                            print('@@@@@@@@@@@@@@@@@@@@@@@@@@')
                                            sub_url = sfs['url']
                                            sub_filename = sfs['f']
                                            sub_dl_name = nsl / sub_filename
                                            print('sub_download_file_name: %s' % sub_dl_name)
                                            urllib.request.urlretrieve(sub_url, sub_dl_name)
                    else:
                        print('no subtitle ID found!')
                else:
                    print('film name less than 3 characters!')
        else:
            print('All films have subtitle!')
    else:
        print('You do not have enough quota to search subtitle of film')